package com.shanshui.test;

import android.os.Bundle;
import android.util.Log;
import android.view.View;

import androidx.appcompat.app.AppCompatActivity;

import com.blankj.utilcode.util.ResourceUtils;
import com.blankj.utilcode.util.Utils;
import com.shanshui.test.gm.GmOkHttpClient;
import com.tencent.kona.crypto.KonaCryptoProvider;
import com.tencent.kona.pkix.KonaPKIXProvider;
import com.tencent.kona.ssl.KonaSSLProvider;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.InetSocketAddress;
import java.security.KeyStore;
import java.security.SecureRandom;
import java.security.Security;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.Collection;
import java.util.Collections;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;

import okhttp3.Call;
import okhttp3.CipherSuite;
import okhttp3.ConnectionSpec;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.TlsVersion;

public class MainActivity2 extends AppCompatActivity {
    private static final String TAG = "MainActivity2";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        Security.addProvider(new KonaCryptoProvider());
        Security.addProvider(new KonaPKIXProvider());
        Security.addProvider(new KonaSSLProvider());
        findViewById(R.id.button4).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        okhttpKona();
                    }
                }).start();
            }
        });
    }

    private void tongsuo() {
//        try {
//            String[] ciphers = {"ECC-SM2-SM4-GCM-SM3"};
//            int port = 1443;
//            X509Certificate caCert = TongsuoX509Certificate.fromX509PemInputStream(getResources().getAssets().open("sm2.trust1.pem"));
//            X509Certificate subCaCert = TongsuoX509Certificate.fromX509PemInputStream(getResources().getAssets().open("sm2.trust2.pem"));
//
//            KeyStore ks = KeyStore.getInstance("PKCS12", new BouncyCastleProvider());
//            ks.load(null);
//            ks.setCertificateEntry("CA", caCert);
//            ks.setCertificateEntry("SUB_CA", subCaCert);
//
//            TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
//            tmf.init(ks);
//            TrustManager[] clientTrustManager = tmf.getTrustManagers();
//
//            SSLContext sslContext = SSLContext.getInstance("TLCP", new TongsuoProvider());
//            sslContext.init(null, clientTrustManager, new SecureRandom());
//            SSLSocketFactory sslCntFactory = sslContext.getSocketFactory();
//            SSLSocket sslSocket = (SSLSocket) sslCntFactory.createSocket("demo.gmssl.cn", port);
//            if (ciphers != null) {
//                sslSocket.setEnabledCipherSuites(ciphers);
//            }
//
//            BufferedWriter out = new BufferedWriter(new OutputStreamWriter(sslSocket.getOutputStream()));
//            out.write("GET / HTTP/1.0\r\n\r\n");
//            out.flush();
//
//            System.out.println("client ssl send msessage success...");
//
//            BufferedInputStream streamReader = new BufferedInputStream(sslSocket.getInputStream());
//            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(streamReader, "utf-8"));
//            String line = null;
//            while((line = bufferedReader.readLine())!= null){
//                System.out.println("client receive server data:" + line);
//            }
//
//            while (true) {
//                try {
//                    sslSocket.sendUrgentData(0xFF);
//                    Thread.sleep(1000L);
//                    System.out.println("client waiting server close");
//                } catch (Exception e) {
//                    bufferedReader.close();
//                    out.close();
//                    sslSocket.close();
//                }
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
    }

    private void okhttpKona() {
        try {
            OkHttpClient client = GmOkHttpClient.getOkHttpClientBuilder(ResourceUtils.readAssets2String("sm2.trust.pem"))
                    .build();
            Request.Builder builder = new Request.Builder()
                    .get()
//                                    .url("https://118.126.45.112:9002/ping");
//                                    .url("https://ebssec.boc.cn");
                    .url("https://demo.gmssl.cn:1443");
            Request request = builder.build();
            Call call = client.newCall(request);
            Response execute = call.execute();
            String string = execute.body().string();
            Log.e(TAG, "run: " + string);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void kona() {
        try {
            // 2. 创建或加载信任库
            KeyStore trustStore = KeyStore.getInstance("PKCS12", "KonaPKIX");
            // 如果是创建新的信任库，需要先load(null)
            trustStore.load(null, null);

            CertificateFactory cf = CertificateFactory.getInstance("X.509", "KonaPKIX");
            // 修改此处：读取多个证书
            Collection<? extends Certificate> certs = cf.generateCertificates(
                    Utils.getApp().getAssets().open("CFCA CS SM2 CA.crt"));

            int index = 0;
            for (Certificate cert : certs) {
                if (cert instanceof X509Certificate) {
                    // 3. 将每个CA证书添加到信任库
                    trustStore.setCertificateEntry("my-ca-alias-" + index++, cert);
                }
            }


            // 4. 创建TrustManagerFactory
//                    TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("SunX509", "KonaSSL");
            TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("PKIX", "KonaSSL");
            trustManagerFactory.init(trustStore);

            SSLContext context = SSLContext.getInstance("TLCPv1.1", "KonaSSL");
//                    context.init(null, new TrustManager[]{new TrustAllManager()}, new SecureRandom());
            context.init(null, trustManagerFactory.getTrustManagers(), new SecureRandom());
            SSLSocketFactory socketFactory = context.getSocketFactory();
            SSLSocket socket = (SSLSocket) socketFactory.createSocket();
            socket.connect(new InetSocketAddress("118.126.45.112", 9002), 2000);
//                    socket.connect(new InetSocketAddress("ebssec.boc.cn", 443), 2000);
            socket.startHandshake();
            Log.e(TAG, "onCreate: " + socket.getSession().getProtocol());
            DataInputStream in = new DataInputStream(socket.getInputStream());
            DataOutputStream out = new DataOutputStream(socket.getOutputStream());

            String data = "GET " + "/ping" + " HTTP/1.1" + "\r\n";
            data += "HOST: " + "221.238.182.5" + ":19002" + "\r\n";
//                    String data = "GET " + "/boc15/login.html" + " HTTP/1.1" + "\r\n";
//                    data += "HOST: " + "ebssec.boc.cn" + ":443" + "\r\n";
            data += "\r\n";
            out.write(data.getBytes());
            out.flush();

            byte[] buf = new byte[8192];
            int len = in.read(buf);
            if (len == -1) {
                System.out.println("eof");
                return;
            }
            Log.e(TAG, "onCreate: " + new String(buf, 0, len));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}